package com.zxy.supplier_system.server.service

import com.zxy.supplier_system.server.controller.MarketShoppingGuideSalaryPlanDetailPreviewController
import com.zxy.supplier_system.server.entity.MarketSaleDocumentItem
import com.zxy.supplier_system.server.entity.MarketSettlementRule
import com.zxy.supplier_system.server.entity.sortByCondition
import com.zxy.supplier_system.server.repository.MarketSaleDocumentRepository
import com.zxy.supplier_system.server.repository.MarketSettlementRuleRepository
import com.zxy.supplier_system.server.utils.orElse404
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional

@Service
class MarketSettlementPlanDetailPreviewService(
    private val systemServiceService: SystemServiceService,
    private val marketSettlementRuleRepository: MarketSettlementRuleRepository,
    private val marketSaleDocumentRepository: MarketSaleDocumentRepository
) {
    @Transactional(readOnly = true)
    fun previewDetail(
        ruleId: Int,
        month: Int,
        year: Int
    ): List<MarketShoppingGuideSalaryPlanDetailPreviewController.MarketShoppingGuideSalaryPlanRuleDetailPreviewResponse> {
        val currentSystemService = systemServiceService.getCurrentSystemService()
        val rule =
            this.marketSettlementRuleRepository.findByIdAndPlan_Market_SystemService(
                ruleId,
                currentSystemService
            ).orElse404()
        val marketSettlementPlan = rule.plan

        val documents =
            marketSaleDocumentRepository.findAllByAccount_Market_IdAndAccount_Market_SystemServiceAndYearAndMonth(
                marketSettlementPlan.market.id,
                currentSystemService,
                year,
                month
            )
        val sortedRules =
            marketSettlementPlan.rules.sortByCondition().filter { it.commissionPercentage != null }
        val goodsList = documents.flatMap { it.goodsList }
        val ruleSaleItemMap =
            computeRuleSaleItemMap(goodsList, sortedRules.subList(0, sortedRules.indexOfFirst { it.id == ruleId } + 1))

        return ruleSaleItemMap[rule]?.map {
            MarketShoppingGuideSalaryPlanDetailPreviewController.MarketShoppingGuideSalaryPlanRuleDetailPreviewResponse(
                it.goods.barcode,
                it.goods.id,
                it.goods.name,
                it.amount,
                it.totalFee
            )
        } ?: emptyList()

    }

    companion object{
        fun computeRuleSaleItemMap(
            allGoodsList: List<MarketSaleDocumentItem>,
            sortedRules: List<MarketSettlementRule>
        ): Map<MarketSettlementRule, List<MarketSaleDocumentItem>> = allGoodsList.groupBy { item ->
            sortedRules.find { rule ->
                rule.commissionPercentage != null && rule.goodsMatcherRule.goodsInScope(item.goods)
            }
        }
            .filter { it.key != null }
            .map { it.key!! to it.value }
            .toMap()
    }

}
